package com.wanxin.wb.common.support;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

import org.apache.ibatis.reflection.ExceptionUtil;
import org.apache.ibatis.session.SqlSession;

/**
 * 
 * <B>Description:</B> <br>
 * <B>Create on:</B> 2015年5月31日 上午9:54:43<br>
 *
 * @param <T>
 * @author 
 * @version 1.0
 */
public class CommodityMapperProxy<T> implements InvocationHandler, Serializable {
    private static final long                        serialVersionUID = -6424540398559729838L;
    private final SqlSession                         sqlSession;
    private final Class<T>                           mapperInterface;
    private final Map<Method, CommodityMapperMethod> methodCache;

    public CommodityMapperProxy(SqlSession sqlSession, Class mapperInterface, Map methodCache) {

        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            try {
                return method.invoke(this, args);
            } catch (Throwable t) {
                throw ExceptionUtil.unwrapThrowable(t);
            }
        }
        /*    Class mapperInterfaceClass = null;
            if (proxy instanceof Proxy) {
                Proxy p = (Proxy) proxy;
                mapperInterfaceClass = ((CommodityMapperProxy) proxy).getMapperInterface();
            }*/
        final CommodityMapperMethod mapperMethod = cachedMapperMethod(method);
        return mapperMethod.execute(sqlSession, args);
    }

    private CommodityMapperMethod cachedMapperMethod(Method method) {
        //String key = mapperInterfaceClass == null ? "" : mapperInterfaceClass.getName();
        //key += "#" + method.getName();
        CommodityMapperMethod mapperMethod = methodCache.get(method);
        if (mapperMethod == null) {
            mapperMethod = new CommodityMapperMethod(mapperInterface, method,
                sqlSession.getConfiguration());
            methodCache.put(method, mapperMethod);
        }
        return mapperMethod;
    }

    public Class<T> getMapperInterface() {
        return mapperInterface;
    }
}
